package com.example.mybatis.plugin;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class DefaultInvocationHandler implements InvocationHandler {

    private final Object target;

    private final Interceptor interceptor;

    public DefaultInvocationHandler(Object target, Interceptor interceptor) {
        this.target = target;
        this.interceptor = interceptor;
    }

    /**
     * 执行对应参数和方法
     * @param proxy
     * @param method
     * @param args
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Invocation invocation = new Invocation(target, method, args);
        return interceptor.intercept(invocation);
    }

    /**
     * 构建代理
     * @param target
     * @param interceptor
     * @return
     */
    public static Object proxy(Object target,Interceptor interceptor){
        DefaultInvocationHandler defaultInvocationHandler =            new DefaultInvocationHandler(target,interceptor);
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),defaultInvocationHandler);
    }
}
